﻿using HslCommunication.Enthernet.Redis;
using Newtonsoft.Json.Linq;
using SYSoft.Comm;
using SYSoft.Comm.Utils;
using SYSoft.Model.Models.DeviceManage.StockCheck;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace SYSoft.Tasks
{
    /// <summary>
    /// 定时任务
    /// </summary>
    public class QuarzTasks
    {
        public QuarzTasks()
        {
            Thread th = new Thread(Dowork);
            th.IsBackground = true;
            th.Start();

        }


        private void Dowork()
        {
            int dayOld = DateTime.Now.Day;
            int hourOld = DateTime.Now.Hour;
            int minOld = DateTime.Now.Minute;
            int count = 0;
            RedisClient redis = new RedisClient("127.0.0.1", 6379, "huibo1206");
            redis.SetPersistentConnection();
            while (true)
            {
                Thread.Sleep(1000);

                var youqi2 = redis.ReadKey("MTCD:PU3000Config");
                if (youqi2.IsSuccess)
                {
                    JObject obj = JObject.Parse(youqi2.Content);
                    ServerInfo.YouQiChanLiang = Convert.ToInt32(obj["ChanLiang"]); //产量                       

                }


                // 每天执行一次
                if (dayOld != DateTime.Now.Day)
                {
                    dayOld = DateTime.Now.Day;
                    CreatCheckTasks();

                }

                // 每小时执行一次
                if (hourOld != DateTime.Now.Hour)
                {
                    hourOld = DateTime.Now.Hour;
         

                }

                // 每分钟执行一次
                if (minOld != DateTime.Now.Minute)
                {
                    minOld = DateTime.Now.Minute;

                    MaintainTasks();
                    count++;
                    if (count > 9)  // 十分钟执行一次
                    {
                        count = 0;
                    }

                }

            }
        }

        /// <summary>
        /// 创建点检任务
        /// </summary>
        private void CreatCheckTasks()
        {
            MysqlHelper mysql = new MysqlHelper(1);
            string sql1 = $"select * from dj_tasks_baselib where CreatTime>'{Convert.ToDateTime("1999-12-12 12:12:12")}'";
            DataTable dt1 = mysql.ExecuteQuery(sql1);
            List<CheckTask_Baselib> list = new List<CheckTask_Baselib>();
            if (dt1 != null && dt1.Rows.Count > 0)
            {
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    list.Add(new CheckTask_Baselib
                    {
                        DeviceId = Convert.ToInt32(dt1.Rows[i]["DeviceId"]),
                        DeviceName = dt1.Rows[i]["DeviceName"].ToString(),
                        DevicePosition = dt1.Rows[i]["DevicePosition"].ToString(),
                        TaskContent = dt1.Rows[i]["TaskContent"].ToString(),
                        TaskName = dt1.Rows[i]["TaskName"].ToString(),
                        TaskImage = dt1.Rows[i]["TaskImage"].ToString(),
                    });
                }
                if (list.Count > 0)
                {
                    List<string> sqls = new List<string>();
                    for (int i = 0; i < list.Count; i++)
                    {
                        string sql = $"insert into dj_tasks (DeviceId,DeviceName,DevicePosition,TaskName,TaskStatus,TaskResult,TaskContent,StartCheckTime,CreatTime,TaskImage,ErrorStatus) values ({list[i].DeviceId}," +
                            $"'{list[i].DeviceName}','{list[i].DevicePosition}','{list[i].TaskName}',{0},{0},'{list[i].TaskContent}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'," +
                            $"'{list[i].TaskImage}',{0})";
                        sqls.Add(sql);
                    }
                    if (mysql.ExecuteCommand(sqls) == 0)
                    {
                        mysql.ExecuteCommand(sqls);
                    }
                    LogHelper.Info("每日任务创建成功！！");
                }
            }
            else
            {
                
            }
           
        }


        /// <summary>
        /// 寻找定时计划执行任务
        /// </summary>
        private void MaintainTasks()
        {
            MysqlHelper mysql = new MysqlHelper();
            string sql2 = $"select * from wh_tasks_baselib where Flag={0} and PlanTime<='{DateTime.Now.ToString()}'";
            DataTable dt = mysql.ExecuteQuery(sql2);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<string> sqls = new List<string>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //LogHelper.Debug("维护日期到：");
                    string sql = $"update wh_tasks_baselib set Flag={1} where Id ={Convert.ToInt32(dt.Rows[i]["Id"])}";
                    string sql1 = $"insert into wh_tasks_data (LibId,DeviceName,TaskName,Flag,TaskContent,PlanTime,CreatTime) values ({Convert.ToInt32(dt.Rows[i]["Id"])}," +
                        $"'{dt.Rows[i]["DeviceName"].ToString()}','{dt.Rows[i]["TaskName"].ToString()}',{1},'{dt.Rows[i]["TaskContent"].ToString()}','{dt.Rows[i]["PlanTime"].ToString()}','{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
                    sqls.Add(sql);
                    sqls.Add(sql1);
                }
                if (sqls.Count > 0)
                {
                    mysql.ExecuteCommandByTran(sqls);
                }
            }
        }

    }
}
